package io.github.shenbinglife.springboot2.layui.common.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ResponseUtils {

    public static void writeObjectAsJson(HttpServletResponse response, Object obj) {
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
            String json = JsonUtils.toJson(obj);
            byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
            response.setContentLength(bytes.length);
            IOUtils.copy(new ByteArrayInputStream(bytes), outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {

        }
    }
}
